/*
 * Copyright 2009 Armando Blancas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package taskgraph.tasks.text;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import taskgraph.Config;
import taskgraph.ports.CharInputPort;
import taskgraph.ports.CharOutputPort;
import taskgraph.tasks.PrimitiveTask;


/**
 * Sorts lines of text.
 *  
 * @author Armando Blancas
 * @see taskgraph.ports.CharInputPort
 * @see taskgraph.ports.CharOutputPort
 */
public class SortLines extends PrimitiveTask {

	private static final int DEFAULT_CAPACITY = Config.get().bufferCapacity();
	
	private CharInputPort input;
	private CharOutputPort output;
	private Comparator<Object> comparator;
	private int bufferSize = DEFAULT_CAPACITY;
	
	/**
	 * This constructor allows creating instances as beans.
	 */
    public SortLines() {
    	// do nothing
    }

	/**
     * Creates an instance for sorting in natural order.
     * 
     * @param input The char input port.
     * @param output The char output port.
     */
    public SortLines(final CharInputPort input, 
    		         final CharOutputPort output) {
    	setInput(input);
    	setOutput(output);
    }

	/**
     * Creates an instance for sorting using the {@code comparator}.
     * 
     * <p>Use the comparator argument to indicate descending order with
     * {@code Collections.reverseOrder()}.
     * 
     * @param input The char input port.
     * @param output The char output port.
     * @param comparator An instance of {@code Comparator<String>}.
     */
    public SortLines(final CharInputPort input, 
    		         final CharOutputPort output,
    		         final Comparator<Object> comparator) {
    	setInput(input);
    	setOutput(output);
    	setComparator(comparator);
    }

	/**
	 * Gets the buffer size for reading chunks of characters.
	 * 
	 * @return the bufferSize
	 */
	public int getBufferSize() {
		return bufferSize;
	}

    /**
	 * Sets the comparator for sorting lines (strings).
	 * 
	 * @return the comparator
	 */
	public Comparator<Object> getComparator() {
		return comparator;
	}

    /**
     * Gets the input port.
     * 
	 * @return The char input port.
	 */
	public CharInputPort getInput() {
		return input;
	}
	
    /**
     * Gets the output port.
     * 
	 * @return The char output port.
	 */
	public CharOutputPort getOutput() {
		return output;
	}

	/**
     * Performs the work of this task.
     * 
	 * Reads lines from the input port, sorts them, and writes the sorted 
	 * lines to the output port. Sorting is done incrementally using a
	 * variable-size data structure to allocate only the required memory.
	 *<pre>
	 *while not EOF
	 *    read a line from input port
	 *    store it in a sorted collection
	 *close input port
	 *while not end of collection
	 *    get the next line
	 *    write it to the output port
	 *close output port
	 *</pre>
	 */
	@Override
    public void run() {
    	try {
    		Set<String> set = new TreeSet<String>();
    		while (!Thread.currentThread().isInterrupted()) {
    			String line = input.readLine();
    			if (line == null) {
    				break;
    			}
    			set.add(line);
            }
    		for (Iterator<String> itor = set.iterator(); itor.hasNext(); ) {
    			output.println(itor.next());
    		}
        } catch (InterruptedIOException ie) {
        	// interruption request
        } catch (IOException ioe) {
        	// pipe synch error
            log.error("SortLines#run()", ioe);
        } finally {
			input.close();
			output.close();
        }
    }

	/**
	 * Sets the buffer size for reading chunks of characters.
	 * <p>The argument should not be less than the default. If it is, the
	 * default size is used instead.
	 * 
	 * @param bufferSize the bufferSize to set
	 */
	public void setBufferSize(final int bufferSize) {
		this.bufferSize = 
			(bufferSize < DEFAULT_CAPACITY) ? DEFAULT_CAPACITY : bufferSize;
	}

	/**
	 * Sets the comparator for sorting lines (strings).
	 * 
	 * @param comparator the comparator to set
	 */
	public void setComparator(Comparator<Object> comparator) {
		this.comparator = comparator;
	}

	/**
	 * Sets the input port.
	 * 
	 * @param input The char input port.
	 */
    public void setInput(final CharInputPort input) {
    	if (input == null)
    		throw new IllegalArgumentException("input == null");
 		this.input = input;
	}

	/**
	 * Sets the output port.
	 * 
	 * @param output The char output port.
	 */
    public void setOutput(final CharOutputPort output) {
    	if (output == null)
    		throw new IllegalArgumentException("output == null");
 		this.output = output;
	}

}
